package com.bignerdranch.android.sensorapplication;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * 文件处理方法
 */
public class FileOperator {
    public static void write(String fileName, String message) {
        try {
            FileWriter writer = new FileWriter(fileName, false);
            writer.write(message);
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void write(String fileName, String message, boolean flag) {
        try {
            FileWriter writer = new FileWriter(fileName, flag);
            writer.write(message);
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static String readFile(String filePath){
        StringBuilder builder = new StringBuilder();
        try {
            String encoding="UTF-8";
            File file=new File(filePath);
            if(file.isFile() && file.exists()){ //判断文件是否存在
                InputStreamReader read = new InputStreamReader(new FileInputStream(file),encoding);//考虑到编码格式
                BufferedReader bufferedReader = new BufferedReader(read);
                String lineTxt;
                //每行内容以/n分隔
                while((lineTxt = bufferedReader.readLine()) != null){
                    lineTxt = lineTxt + "\n";
                    builder.append(lineTxt);
                }
                read.close();
            }else{
                System.out.println("找不到指定的文件");
            }
        } catch (Exception e) {
            System.out.println("读取文件内容出错");
            e.printStackTrace();
        }
        return builder.toString();
    }

    public static void directMakeDir(String fileName) {
        File file = new File(fileName);
        if (!file.exists()) {
            file.mkdir();
        }
    }

    public static boolean renameFile(String oldPath, String newPath) {
        File oldFile = new File(oldPath);
        File newFile = new File(newPath);
        return oldFile.renameTo(newFile);
    }
}
